<template>
  <div class="map-nav">
    <el-menu mode="horizontal" :default-active="activeIndex" @select="handleSelect">
      <div class="left">
        <div class="logo">光谷智慧交通</div>
        <slot>
          <!-- 使用 hoverIndex 控制高亮 -->
          <el-menu-item
            v-for="item in menuItems"
            :key="item.index"
            :class="{ 'hover-active': hoverIndex === item.index }"
            @mouseenter="handleMouseEnter(item.index)"
            @mouseleave="handleMouseLeave(item.index)"
          >
            {{ item.label }}
          </el-menu-item>
        </slot>
      </div>
      <div class="right">
        <event-search @close="handleSearchClose"></event-search>
        <el-select :placeholder="username">
          <el-option value="exit" @click="handleExit">退出登录</el-option>
        </el-select>
        <img :src="logImg" alt="" />
      </div>
    </el-menu>
  </div>
</template>

<script setup>
import { ref, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import EventSearch from './common/EventSearch.vue'

const route = useRoute()
const router = useRouter()

// 菜单选中状态 (用于点击)
const activeIndex = ref('')
// 悬停状态 (用于鼠标高亮)
const hoverIndex = ref(null)
let timeoutId = null

// 用户名和 logo
const username = route.query.username
const logImg = `/images/${route.name}.png`

// 菜单项数据
const menuItems = [
  { index: '1', label: '路况报告' },
  { index: '2', label: '实时交通' },
]

// 鼠标进入时立即高亮
const handleMouseEnter = (index) => {
  clearTimeout(timeoutId) // 清除之前的延迟
  hoverIndex.value = index
}

// 鼠标离开时延迟移除
const handleMouseLeave = (index) => {
  timeoutId = setTimeout(() => {
    if (hoverIndex.value === index) {
      hoverIndex.value = null
    }
  }, 2000)
}

// 清理定时器
onBeforeUnmount(() => {
  clearTimeout(timeoutId)
})

// 菜单选中事件
const handleSelect = (key) => {
  activeIndex.value = key
  console.log('Selected:', key)
}

// 搜索弹窗关闭
const handleSearchClose = () => {
  activeIndex.value = ''
}

// 退出登录
const handleExit = async () => {
  try {
    // 通过用户名获取用户信息
    const username = route.query.username
    const { data } = await axios.post('http://localhost:3001/getuserbyname', { username })
    const userId = data.data.data[0].id
    const token = localStorage.getItem('token')

    // 更新用户的 isOnline 状态为 false
    await axios.put(
      'http://localhost:3001/updateuser',
      {
        id: userId,
        userObj: { isOnline: false },
      },
      { headers: { Authorization: `Bearer ${token}` } },
    )

    // 清除本地存储的 token和userId
    localStorage.removeItem('token')
    localStorage.removeItem('userId')
    ElMessage.warning('已退出登录')
    router.push('/login')
  } catch (error) {
    console.error('更新用户在线状态出错:', error)
    ElMessage.error('更新用户在线状态出错，请稍后重试')
  }
}
</script>

<style lang="scss" scoped>
.map-nav {
  // 穿透 Element Plus 组件样式
  :deep(.el-menu--horizontal) {
    .el-menu-item {
      transition: background-color 0.3s; // 平滑过渡

      &:hover {
        background-color: var(--el-color-primary-light-9);
        transition: background-color 0.3s;
      }

      &.is-active {
        background-color: inherit !important;
        color: var(--el-color-primary);
        color: inherit !important;
      }

      // 覆盖默认选中样式
      &.hover-active {
        background-color: var(--el-color-primary-light-9) !important;

        &::after {
          /* 隐藏底部线条 */
          display: none !important;
        }
      }

      // 保留点击选中样式（如果需要）
      // &.is-active {
      //   background-color: var(--el-color-primary-light-8);
      // }
    }
  }

  // 其他原有样式保持不变
  .el-menu {
    z-index: 200;
    justify-content: space-between;
    align-items: center;
    user-select: none;
    padding: 0 10px;
    border: none;

    .left {
      display: flex;
      align-items: center;
      flex-shrink: 0;

      .logo {
        font-size: 24px;
        font-weight: 600;
        cursor: pointer;
      }
    }

    .right {
      flex-shrink: 0;
      display: flex;
      align-items: center;
      gap: 20px;

      :deep(.el-input) {
        min-width: 260px;
      }

      .el-select {
        min-width: 150px;
      }

      img {
        width: 22px;
        height: 22px;
      }
    }
  }
}
</style>
